package com.hssy.wululuaplan.exception;


import com.hssy.wululuaplan.common.Result;
import com.hssy.wululuaplan.constants.enums.ExceptionEnum;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理
 * @author Mr.Hongtao
 */
@Order(-1)
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<ExceptionEnum> error(Exception e) {
        e.printStackTrace();
        return Result.error(ExceptionEnum.error.getCode(),ExceptionEnum.error.getMessage());
    }


    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result<ExceptionEnum> error(ArithmeticException e) {
        e.printStackTrace();
        return Result.error(ExceptionEnum.arithmeticException.getCode(), ExceptionEnum.arithmeticException.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<ExceptionEnum> error(MethodArgumentNotValidException e) {
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        // Map<String,String> errorMap = new HashMap<>();
        // bindingResult.getFieldErrors().forEach((fieldError)->{
        //     errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        // });
        String defaultMessage = bindingResult.getFieldErrors().get(0).getDefaultMessage();
        return Result.error(-1000,defaultMessage );
    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Result<ExceptionEnum> error(CustomException e) {
        e.printStackTrace();
        return Result.error(e.getCode(), e.getMsg());
    }
}